package com.laihui.fragment;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.laihui.MyApplication;
import com.laihui.activity.BindCardActivity;
import com.laihui.activity.InviteActivity;
import com.laihui.activity.R;
import com.laihui.activity.AvailableCapitalActivity;
import com.laihui.activity.BankCardActivity;
import com.laihui.activity.DiscountCouponActivity;
import com.laihui.activity.LoginActivity;
import com.laihui.activity.MyInvestActivity;
import com.laihui.activity.RealnameActivity;
import com.laihui.activity.RechargeActivity;
import com.laihui.activity.SafeCenterActivity;
import com.laihui.activity.WithDrawActivity;
import com.laihui.base.BaseFragment;
import com.laihui.entity.Account;
import com.laihui.entity.MemberBank;
import com.laihui.entity.RealBean;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 我的投资页面
 */
public class Index3Fragment extends BaseFragment {

    @BindView(R.id.tv_use_money)
    TextView tv_use_money;
    @BindView(R.id.tv_total_money)
    TextView tv_total_money;
    @BindView(R.id.tv_total_income)
    TextView tv_total_income;

    @BindView(R.id.ll_recharge)//充值
            LinearLayout ll_recharge;


    @BindView(R.id.ll_cash)//充值
            LinearLayout ll_cash;
    @BindView(R.id.ll_my_tender)//充值
            LinearLayout ll_my_tender;
    @BindView(R.id.ll_account_log)//充值
            LinearLayout ll_account_log;
    @BindView(R.id.ll_coupon)//充值
            LinearLayout ll_coupon;
    @BindView(R.id.ll_card_manage)//充值
            LinearLayout ll_card_manage;
    @BindView(R.id.ll_safecenter)//充值
            LinearLayout ll_safecenter;




    private static boolean isRealName = false ;//是否实名认证的标志
    private static boolean isBindBankCard = false ;//是否绑定银行卡的标志

    private Activity mActivity;
    private MyApplication application;
    private DecimalFormat df = new DecimalFormat("0.00");
    private DecimalFormat df1 = new DecimalFormat("0");
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.action.user.exit")) {
              //  exit();
            } else if (intent.getAction().equals("android.action.toWithDraw")) {

            } else if (intent.getAction().equals("android.action.refresh")) {
                loadData();

                //getHotSale(true);
            }
        }
    };

    //是否实名认证
    private void isReal() {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", application.userId);
        application.apiService.toReal(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RealBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(RealBean toRealname) {

                        if (toRealname.item!=null) {
                            isRealName = true;
                        } else {
                            isRealName = false;
                        }
                    }
                });
    }

    //是否绑定银行卡
    private void isBind() {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", application.userId);
        application.apiService.isBankBind(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<MemberBank>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(MemberBank bankCard) {
                        if (bankCard.item!=null) {
                            isBindBankCard = true;
                        } else {
                            isBindBankCard = false;
                        }
                    }
                });
    }



    @Override
    public void init() {
        mActivity = getActivity();
        application = (MyApplication) mActivity.getApplication();
       // loadData();
        isReal();
        isBind();
    }
    //如果登录的话这些显示出来
    private void loadData() {
        if (application.isLogin) {
            Map<String, String> map = new HashMap<>();
            map.put("member_id", String.valueOf(application.userId) + "");
            //加载总资产，累计收益，代收收益，头像旁边的手机号
            application.apiService.getAccount(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Account>() {
                        @Override
                        public void onCompleted() {

                        }
                        @Override
                        public void onError(Throwable e) {
                            Log.e("Index3Fragment", "onError: " + e.toString());
                        }

                        @Override
                        public void onNext(Account account) {
                            tv_total_money.setText(df.format(account.item.balance));//可用余额
                            tv_use_money.setText(df.format(account.item.collection));//待收金额
                            tv_total_income.setText(df.format(account.item.freezing_amont));//冻结金额
                        }
                    });
        }else{
            startActivity(new Intent(mActivity, LoginActivity.class));
        }
    }

    @Override
    public void onResume() {
        isBind();
        isReal();
        super.onResume();
       // this.isVisibleToUser=isVisibleToUser;
        if (!application.isLogin&isVisibleToUser) {
            startActivity(new Intent(mActivity, LoginActivity.class));
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.action.user.exit");
        filter.addAction("android.action.toWithDraw");
        filter.addAction("android.action.refresh");
        mActivity.registerReceiver(receiver, filter);

        refresh();
    }

    boolean isVisibleToUser;
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            this.isVisibleToUser=isVisibleToUser;
            if (!application.isLogin) {
                startActivity(new Intent(mActivity, LoginActivity.class));
            }
        } else {
            //TODO now it's invisible to user
        }
    }

    public void refresh(){
        loadData();
    }


                @Override
    public int getFragmentId() {
        return R.layout.fragment_index3;

    }

    @Override
    public Object bindFragment() {
        return this;

    }
    @OnClick({R.id.ll_invite,R.id.ll_recharge,R.id.ll_cash,R.id.ll_my_tender,R.id.ll_account_log,R.id.ll_coupon,R.id.ll_card_manage,R.id.ll_safecenter})
    public void onViewClicked(View view) {
        if (!application.isLogin) {
            startActivity(new Intent(mActivity, LoginActivity.class));
        }else{
            switch (view.getId()) {
                case R.id.ll_invite:
                    if (!application.isLogin) {
                        startActivity(new Intent(mActivity, LoginActivity.class));
                    } else {

                        startActivity(new Intent(mActivity, InviteActivity.class));
                    }
                    break;

                case R.id.ll_recharge://充值
                    if (!isRealName) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity) ;
                        builder.setTitle("是否实名认证");
                        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                startActivity(new Intent(mActivity, RealnameActivity.class));
                            }
                        }) ;

                        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }) ;
                        AlertDialog alertDialog = builder.create() ;
                        alertDialog.show();
                        return;

                    } else if (!isBindBankCard) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity) ;
                        builder.setTitle("是否绑定银行卡");
                        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivity(new Intent(mActivity, BindCardActivity.class));
                            }
                        }) ;


                        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }) ;
                        AlertDialog alertDialog = builder.create() ;
                        alertDialog.show();

                    } else {
                        startActivity(new Intent(mActivity, RechargeActivity.class));
                    }


                    break;
                case R.id.ll_my_tender://我的投资
                    startActivity(new Intent(mActivity, MyInvestActivity.class));
                    break;
                /*case R.id.ll_balance://账户余额
                    break;*/
                case R.id.ll_coupon://优惠券
                    startActivity(new Intent(mActivity, DiscountCouponActivity.class));
                    break;
                case R.id.ll_account_log://资金记录
//                    startActivity(new Intent(mActivity, MoneyRecordDetailActivityNew.class));
                    startActivity(new Intent(mActivity, AvailableCapitalActivity.class));
                    break;

                case  R.id.ll_safecenter:
                    startActivity(new Intent(mActivity, SafeCenterActivity.class));
                    break;

                case R.id.ll_cash://提现
                    if (!isRealName) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity) ;
                        builder.setTitle("是否实名认证");
                        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                startActivity(new Intent(mActivity, RealnameActivity.class));
                            }
                        }) ;

                        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }) ;
                        AlertDialog alertDialog = builder.create() ;
                        alertDialog.show();
                        return;

                    } else if (!isBindBankCard) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity) ;
                        builder.setTitle("是否绑定银行卡");
                        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivity(new Intent(mActivity, BindCardActivity.class));
                            }
                        }) ;


                        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }) ;
                        AlertDialog alertDialog = builder.create() ;
                        alertDialog.show();

                    } else {
                        startActivity(new Intent(mActivity, WithDrawActivity.class));
                    }

                    break;
                case R.id.ll_card_manage://银行卡

                    Map<String, String> map1 = new HashMap<>();
                    map1.put("member_id", application.userId);
                    application.apiService.isBankBind(map1)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Subscriber<MemberBank>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {
                                    Log.e("e",e.toString());
                                }


                                public void onNext(MemberBank memberBank) {
                                    if (memberBank.item==null) {
                                        startActivity(new Intent(mActivity,BindCardActivity.class));
                                    } else  {
                                        startActivity(new Intent(mActivity,  BankCardActivity.class));
                                    }
                                }
                            });
                    break;
            }
        }
    }
}
